# AI分析定时任务管理命令
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
import logging

from assets.models import Asset, MaintenanceRecord
from assets.models_ai import AssetRecommendation, AssetAnomalyDetection
from assets.ai_engine import ai_recommendation_engine, anomaly_detection_service

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = '运行AI分析任务，生成推荐和检测异常'

    def add_arguments(self, parser):
        parser.add_argument(
            '--type',
            type=str,
            choices=['recommendations', 'anomalies', 'all'],
            default='all',
            help='指定运行的分析类型'
        )
        parser.add_argument(
            '--user-id',
            type=int,
            help='指定用户ID，用于生成推荐'
        )
        parser.add_argument(
            '--clean-old',
            action='store_true',
            help='清理过期的推荐和已解决的异常'
        )
        parser.add_argument(
            '--days-old',
            type=int,
            default=30,
            help='清理多少天前的旧数据'
        )

    def handle(self, *args, **options):
        analysis_type = options['type']
        user_id = options['user_id']
        clean_old = options['clean_old']
        days_old = options['days_old']

        self.stdout.write(
            self.style.SUCCESS(f'开始运行AI分析任务 - 类型: {analysis_type}')
        )

        try:
            # 清理旧数据
            if clean_old:
                self.clean_old_data(days_old)

            # 运行推荐生成
            if analysis_type in ['recommendations', 'all']:
                self.generate_recommendations(user_id)

            # 运行异常检测
            if analysis_type in ['anomalies', 'all']:
                self.detect_anomalies()

            self.stdout.write(
                self.style.SUCCESS('AI分析任务完成')
            )

        except Exception as e:
            logger.error(f'AI分析任务执行失败: {e}')
            self.stdout.write(
                self.style.ERROR(f'AI分析任务执行失败: {e}')
            )

    def clean_old_data(self, days_old):
        """清理旧数据"""
        cutoff_date = timezone.now() - timedelta(days=days_old)
        
        # 清理过期的推荐
        expired_recommendations = AssetRecommendation.objects.filter(
            created_at__lt=cutoff_date,
            is_dismissed=True
        )
        expired_count = expired_recommendations.count()
        expired_recommendations.delete()
        
        # 清理已解决的异常
        resolved_anomalies = AssetAnomalyDetection.objects.filter(
            detected_at__lt=cutoff_date,
            is_resolved=True
        )
        resolved_count = resolved_anomalies.count()
        resolved_anomalies.delete()
        
        self.stdout.write(
            self.style.SUCCESS(
                f'清理完成 - 删除了 {expired_count} 个过期推荐和 {resolved_count} 个已解决异常'
            )
        )

    def generate_recommendations(self, user_id=None):
        """生成推荐"""
        self.stdout.write('正在生成AI推荐...')
        
        # 获取用户
        if user_id:
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                self.stdout.write(
                    self.style.ERROR(f'用户ID {user_id} 不存在')
                )
                return
        else:
            # 使用第一个超级用户
            user = User.objects.filter(is_superuser=True).first()
            if not user:
                self.stdout.write(
                    self.style.ERROR('没有找到可用的用户')
                )
                return

        total_recommendations = 0

        try:
            # 生成维修推荐
            maintenance_recs = ai_recommendation_engine.generate_maintenance_recommendations(user)
            maintenance_count = len(maintenance_recs)
            total_recommendations += maintenance_count
            
            self.stdout.write(f'生成了 {maintenance_count} 个维修推荐')

            # 生成更换推荐
            replacement_recs = ai_recommendation_engine.generate_replacement_recommendations(user)
            replacement_count = len(replacement_recs)
            total_recommendations += replacement_count
            
            self.stdout.write(f'生成了 {replacement_count} 个更换推荐')

            # 生成优化推荐
            optimization_recs = ai_recommendation_engine.generate_optimization_recommendations(user)
            optimization_count = len(optimization_recs)
            total_recommendations += optimization_count
            
            self.stdout.write(f'生成了 {optimization_count} 个优化推荐')

            self.stdout.write(
                self.style.SUCCESS(f'推荐生成完成 - 总计: {total_recommendations} 个推荐')
            )

        except Exception as e:
            logger.error(f'生成推荐时出错: {e}')
            self.stdout.write(
                self.style.ERROR(f'生成推荐失败: {e}')
            )

    def detect_anomalies(self):
        """检测异常"""
        self.stdout.write('正在运行异常检测...')
        
        total_anomalies = 0

        try:
            # 获取所有在用资产
            assets = Asset.objects.filter(status='in_use')
            
            for asset in assets:
                # 使用模式异常检测
                usage_anomaly = anomaly_detection_service.detect_usage_anomalies(asset)
                if usage_anomaly:
                    total_anomalies += 1
                    self.stdout.write(f'检测到使用异常: {asset.name}')

                # 维修频率异常检测
                frequency_anomaly = anomaly_detection_service.detect_frequency_anomalies(asset)
                if frequency_anomaly:
                    total_anomalies += 1
                    self.stdout.write(f'检测到频率异常: {asset.name}')

            # 成本异常检测
            recent_maintenance = MaintenanceRecord.objects.filter(
                created_at__gte=timezone.now() - timedelta(days=90)
            )
            cost_anomalies = anomaly_detection_service.detect_cost_anomalies(list(recent_maintenance))
            cost_anomaly_count = len(cost_anomalies)
            total_anomalies += cost_anomaly_count
            
            if cost_anomaly_count > 0:
                self.stdout.write(f'检测到 {cost_anomaly_count} 个成本异常')

            self.stdout.write(
                self.style.SUCCESS(f'异常检测完成 - 总计: {total_anomalies} 个异常')
            )

        except Exception as e:
            logger.error(f'异常检测时出错: {e}')
            self.stdout.write(
                self.style.ERROR(f'异常检测失败: {e}')
            )

    def get_system_stats(self):
        """获取系统统计信息"""
        stats = {
            'total_assets': Asset.objects.count(),
            'active_assets': Asset.objects.filter(status='in_use').count(),
            'total_recommendations': AssetRecommendation.objects.count(),
            'unread_recommendations': AssetRecommendation.objects.filter(is_read=False).count(),
            'active_anomalies': AssetAnomalyDetection.objects.filter(is_resolved=False).count(),
            'resolved_anomalies': AssetAnomalyDetection.objects.filter(is_resolved=True).count(),
        }
        
        self.stdout.write('系统统计信息:')
        for key, value in stats.items():
            self.stdout.write(f'  {key}: {value}')
        
        return stats